package mylibrary.security.UDPChat;

import java.io.ByteArrayOutputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;

public class UDPSocket {

	private byte[] buffer = new byte[1024];
	private DatagramSocket receiveSocket;
	private DatagramSocket sendSocket;
	private String remoteHost;
	private int sendPort;
	
	public UDPSocket(String localHost, String remoteHost, int receivePort, int sendPort) throws Exception {
		this.remoteHost = remoteHost;
		this.sendPort = sendPort;
		
		this.receiveSocket = new DatagramSocket(new InetSocketAddress(localHost, receivePort));
		this.sendSocket = new DatagramSocket();
	}
	
	public byte[] receive() throws Exception {
		DatagramPacket dp = new DatagramPacket(buffer, buffer.length);
		receiveSocket.receive(dp);
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		baos.write(dp.getData(), 0, dp.getLength());
		byte[] data = baos.toByteArray();
		baos.close();
		return data;
	}
	
	public void send(byte[] data) throws Exception {
		DatagramPacket dp = new DatagramPacket(buffer, buffer.length, InetAddress.getByName(remoteHost), sendPort);
		dp.setData(data);
		sendSocket.send(dp);
	}
	
	public void close() {
		try {
			if(receiveSocket.isConnected()) {
				receiveSocket.disconnect();
				receiveSocket.close();
			}
			if(sendSocket.isConnected()) {
				sendSocket.disconnect();
				sendSocket.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
